<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/15
 * Time: 12:43
 */
namespace frontend\modules\v1\controllers;
use common\models\Code;
use frontend\controllers\BaseController;
use frontend\models\Rest;
use Yii;
use yii\db\Query;

/**
 * Class BusinessController
 * @package frontend\modules\v1\controllers
 */
class CodeController extends BaseController {

    /**
     * 接收请求
     * @param phone
     */
    public function actionReceive(){
        /** 校验表单是否为空 */
        if(!$this->postData){
            return $this->responseError("参数信息为空.");
        }
        /** 校验phone */
        if(empty($this->postData['phone'])){
            return $this->responseError('phone is null');
        }

        $phone = $this->postData['phone'];
        if(!preg_match("/^1[3|4|5|7|8]{1}[0-9]{9}$/", $phone)) {
            return $this->responseError('phone is Error');
        }
        $randnum = rand(1000,9999);
        $d = time();
        $query = new Query();
        $data = $query->select(['code','created_at'])->from('code')
            ->where(['and', 'mobile='.$phone])
            ->orderBy(['created_at' => SORT_DESC])
            ->limit(1)
            ->all();
        if($data){
            $data = $data[0];
            $createAt = $data['created_at'] + 60;
            if($createAt >= $d){
                return $this->responseError('code is already.');
            }
        }
        unset($query);
        /** 发送短信 */
        $result = $this->voiceVerify($randnum, "3", $phone, "18511599225", "营销外呼状态通知回调地址",'zh','ok');
        if(!$result){
            return $this->responseError('code is Error');
        }
        /** 插入验证码 */
        $sql = "insert into code(mobile,type,code,created_at) value(:mobile,:type,:code,:created_at)";
        $command = Yii::$app->db->createCommand($sql);
        $command->bindValues(array(
            ':mobile' => $phone,
            ':type' => "Login",
            ':code' => $randnum,
            ':created_at' => time()
        ));
        $command->execute();
        return $this->responseFormat(array('info' => "success"));
    }

    /**
     * 发送模板短信
     * @param to 手机号码集合,用英文逗号分开
     * @param datas 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
     * @param $tempId 模板Id
     */
    function sendTemplateSMS($to,$datas,$tempId)
    {
        $accountSid = Yii::$app->params['accountSid'];
        $accountToken = Yii::$app->params['accountToken'];
        $appId = Yii::$app->params['appId'];
        $serverIP = Yii::$app->params['serverIP'];
        $serverPort = Yii::$app->params['serverPort'];
        $softVersion = Yii::$app->params['softVersion'];

        // 初始化REST SDK
        $rest = new Rest($serverIP,$serverPort,$softVersion);
        $rest->setAccount($accountSid,$accountToken);
        $rest->setAppId($appId);

        // 发送模板短信
        $result = $rest->sendTemplateSMS($to,$datas,$tempId);
        if($result == NULL ) {
            return "";
        }
        if($result->statusCode != 0) {

            return "";
        }else{
            echo "Sendind TemplateSMS success!<br/>";
            $smsmessage = $result->TemplateSMS;
            return "success";
        }
    }

    /**
     * 语音验证码
     * @param verifyCode 验证码内容，为数字和英文字母，不区分大小写，长度4-8位
     * @param playTimes 播放次数，1－3次
     * @param to 接收号码
     * @param displayNum 显示的主叫号码
     * @param respUrl 语音验证码状态通知回调地址，云通讯平台将向该Url地址发送呼叫结果通知
     * @param lang 语言类型。取值en（英文）、zh（中文），默认值zh。
     * @param userData 第三方私有数据
     */
    function voiceVerify($verifyCode,$playTimes,$to,$displayNum,$respUrl,$lang,$userData)
    {
        $accountSid = Yii::$app->params['accountSid'];
        $accountToken = Yii::$app->params['accountToken'];
        $appId = Yii::$app->params['appId'];
        $serverIP = Yii::$app->params['serverIP'];
        $serverPort = Yii::$app->params['serverPort'];
        $softVersion = Yii::$app->params['softVersion'];
        /** 初始化REST SDK */
        $rest = new Rest($serverIP,$serverPort,$softVersion);
        $rest->setAccount($accountSid,$accountToken);
        $rest->setAppId($appId);

        //调用语音验证码接口
        $result = $rest->voiceVerify($verifyCode,$playTimes,$to,$displayNum,$respUrl,$lang,$userData);
        if($result == NULL ) {
            return "";
        }

        if($result->statusCode!=0) {
            return "";
        } else{
//            echo "voiceverify success!<br>";
            $voiceVerify = $result->VoiceVerify;
//            echo "callSid:".$voiceVerify->callSid."<br/>";
//            echo "dateCreated:".$voiceVerify->dateCreated."<br/>";
            return "success";
        }
    }
}